<?php
declare (strict_types=1);

namespace app\common\customer\model;

use app\common\config\logic\Dictionary;
use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigSource;
use app\common\config\model\ConfigStatus;
use app\common\customer\logic\AllocateLogic;
use app\common\customer\logic\ContactLogic;
use app\common\customer\logic\CustomerTagLogic;
use app\common\order\model\OrderBom;
use app\common\product\logic\StoreCategoryLogic;
use app\common\system\logic\DepartmentLogic;
use app\common\system\logic\UserLogic;
use think\Model;
use think\model\concern\SoftDelete;
use think\Request;
use util\Format;

class Customer extends Model
{
    protected $table = "tk_member";
    
    use SoftDelete;
    protected $defaultSoftDelete = 0;

    protected $type = [
        'next_visit_time' => 'timestamp',
    ];

    // 获取联系方式
    public function getContactAttr($value, $data)
    {
        $contactLogic = new ContactLogic();
        $row = $contactLogic->getContactDefault($data['id'], ['id', 'role_type', 'contact_type', 'tag', 'contact']);
        if (!empty($row)) {
            $row['contact'] = Format::mobile($row['contact']);
        } else {
            $row['contact'] = '';
        }

        return $row;
    }

    // 获取所有联系方式
    public function getContactsAttr($value, $data)
    {
        $contactModel = new CustomerContact();
        // 只要contact字段
        return $contactModel->where('member_id', $data['id'])->column('id, contact');
    }

    // 获取渠道对象
    public function getSourceAttr($value, $data)
    {
        if(empty($data['source_id']))  {
            return [
                'id' => '',
                'title' => ''
            ];
        };
        
        $logic = new DictionaryLogic();
        return $logic->getFullPath($data['source_id']);
    }

    // 获取重复渠道名称
    public function getSourcesAttr($value, $data)
    {
        $memberSourceModel = new CustomerSource();
        $ids = $memberSourceModel->where('member_id', $data['id'])->column('source_id');
        if (empty($ids)) return [];

        $fullPath = [];
        $logic = new DictionaryLogic();
        foreach ($ids as $id) {
            $fullPath[] = $logic->getFullPath($id);
        }

        return $fullPath;
    }

    // 获取当前创建者所在的部门，如果当前账号存在多部门，则部门字段必选
    public function getDepartmentAttr($value, $data)
    {
        $logic = new DepartmentLogic();
        return $logic->getDepartment($data['department_id'], ['id', 'title']);
    }

    // 获取创建者对象
    public function getCreatorAttr($value, $data)
    {
        $logic = new UserLogic();

        return $logic->getUser($data['create_id'], ['id', 'realname', 'mobile', 'avatar']);
    }

    public function getVisitStatusAttr($value, $data) {
        $dictionaryLogic = new DictionaryLogic();
        $row = $dictionaryLogic->getItem($data['status'], ConfigStatus::class, ['id','title']);
        if (empty($row)) {
            $row = [
                'id' => 0,
                'title' => '待跟进'
            ];
        }

        return $row;
    }

    public function getTagAttr($value, $data)
    {
        $logic = new CustomerTagLogic();
        return $logic->getMemberTag($data['id']);
    }


    public function getAllocateAttr($value, $data)
    {
        $logic = new AllocateLogic();
        return $logic->getAllocate($data['id'], $data['create_id'], ['assign_status', 'next_visit_time']);
    }

    public function getCategoryAttr($value, $data) {
        $categoryLogic = new StoreCategoryLogic();
        return $categoryLogic->getStoreCategory($data['category_id'], ['id', 'title', 'customer_model', 'order_model', 'on_member_company', 'is_sale']);
    }

    // 获取客服跟进人
    public function getUserAttr($value, $data) {
       // 获取所有推广客服
    }

    // 获取邀约信息
    public function getInviteAttr($value, $data) {
        $customerInviteModel = new CustomerInvite();
        $rows = $customerInviteModel->where('member_id', $data['id'])->order('id asc')->select();
        $invite = [
            'store' => '',
            'first_visit' => [
                'visit_time' => '',
                'remark' => '',
            ],
            'second_visit' => [
                'visit_time' => '',
                'remark' => '',
            ],
            'third_visit' => [
                'visit_time' => '',
                'remark' => '',
            ],
        ];

        if ($rows->isEmpty()) return $invite;

        $store = '';
        foreach ($rows as $row) {
            $row->append(['store']);
            $store = $row->store['title'];
            break;
        }

        $row = $rows->first();
        // 第一次邀约
        $invite['store'] = $store;
        $invite['first_visit']['visit_time'] = $row->visit_time;
        $invite['first_visit']['remark'] = $row->remark;

        // 移到下一个
        $rows->shift();

        $row = $rows->first();
        if ($rows->isEmpty()) {
            // 第二次邀约
            $invite['second_visit']['visit_time'] = '';
            $invite['second_visit']['remark'] = '';
        } else {
            // 第二次邀约
            $invite['second_visit']['visit_time'] = $row->visit_time;
            $invite['second_visit']['remark'] = $row->remark;
        }

        // 移到下一个
        $rows->shift();

        $row = $rows->first();
        if ($rows->isEmpty()) {
            // 第三次邀约
            $invite['third_visit']['visit_time'] = '';
            $invite['third_visit']['remark'] = '';
        } else {
            // 第三次邀约
            $invite['third_visit']['visit_time'] = $row->visit_time;
            $invite['third_visit']['remark'] = $row->remark;
        }

        return $invite;
    }

    // 获取订单信息
    public function getOrderAttr($value, $data) {
        $model = new OrderBom();
        
        $row = $model->where('member_id', $data['id'])->order('id desc')->find();
        if (!$row) return [
            'user' => [
                'id' => '',
                'realname' => '',
            ],
            'sign_date' => '',
            'totals' => '',
        ];

        $row->append(['user']);

        return [
            'user' => [
                'id' => $row['user']['id'],
                'realname' => $row['user']['realname'],
            ],
            'sign_date' => $row['sign_date'],
            'totals' => $row['totals'],
        ];
    }
}
